package cn.hss.jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**使用JDBC操作数据实现新增
 * @author 作者：HeShaoShuai
 * @Email 邮箱：2569819541@qq.com
 * @Date 日期：2023/5/5 15:21
 * @Package 包名：cn.hss.jdbc
 * @Project 项目名：JavaSE
 * @Version 1.0
 */
public class JDBCAdd {
	public static void main(String[] args) {
		Connection conn = null;
		PreparedStatement ps = null;
		try {
			//2.注册驱动
			Class.forName("com.mysql.cj.jdbc.Driver");
			//3.获取数据库连接对象Connection
			conn = DriverManager.getConnection(
					"jdbc:mysql://localhost:3306/hlp_db",
					"root",
					"2399430940");
			//4.定义sql
			String sql = "insert into account values(?,?,?)";
			//5.创建执行sql的对象
			ps = conn.prepareStatement(sql);
			//5.1 设置占位符的值
			ps.setObject(1, null);
			ps.setString(2, "何少帅");
			ps.setObject(3, 1000);
			//6.执行sql,调用方法去接受返回结果
			int rows = ps.executeUpdate();
			//7.处理结果
			if (rows > 0) {
				System.out.println("新增成功，影响了" + rows + "行记录");
			} else {
				System.out.println("新增失败！！！");
			}
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			//8.释放资源
			if (ps != null) {
				try {
					ps.close();
				} catch (SQLException throwables) {
					throwables.printStackTrace();
				}
			}
			if (conn != null) {
				try {
					conn.close();
				} catch (SQLException throwables) {
					throwables.printStackTrace();
				}
			}
		}
	}
}
